﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace Utils.Common
{
  public  class XmlHelper
    {

        //实体转XML
      public static string XmlSerialize<T>(T obj,string filename)
      {
          var utf8WithoutBom = new System.Text.UTF8Encoding(false);
          using (StreamWriter sw = new StreamWriter(filename, false, utf8WithoutBom))
          {
              Type t = obj.GetType();
              XmlSerializer serializer = new XmlSerializer(obj.GetType());
              serializer.Serialize(sw, obj);
              sw.Close();
              return sw.ToString();
          }
      }


      //XML转实体
      public static T DESerializer<T>(string strXML) where T : class
      {
          try
          {
              using (StringReader sr = new StringReader(strXML))
              {
                  var serializer = new XmlSerializer(typeof(T));
                  return serializer.Deserialize(sr) as T;
              }
          }
          catch (Exception ex)
          {
              return null;
          }
      }

      //c#文件流读文件 
      public static string ReadFile(string filename)
      {
        
          using (FileStream fsRead = new FileStream(filename, FileMode.Open))
          {
              int fsLen = (int)fsRead.Length;
              byte[] heByte = new byte[fsLen];
              int r = fsRead.Read(heByte, 0, heByte.Length);
              string myStr = System.Text.Encoding.UTF8.GetString(heByte);
              return myStr;
          } 
      }


      //XML转实体
      public static T DESerializerByPath<T>(string filename) where T : class
      {
          return DESerializer<T>(ReadFile(filename));
      }

    }
}
